<?php
//
// Pull the first link from google news. Assume its the most relevant.
//
function get_google_news($gurl) {
	// Initialize the cURL session with the request URL
	$session = curl_init($gurl);
	
	// Tell cURL to return the request data
	curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
	
	// Execute cURL on the session handle
	$response = curl_exec($session);
	if($response === false) {
		echo "google results failed<p>";
		return "";
	}
	
	curl_close($session);
	
	$xml = new SimpleXMLElement($response);
	
	global $gRandomNews;
	
	if($gRandomNews == true) {
		$index = rand(1,9);
		echo "<!-- <h4>2. Randomnews is true, index is " . $index . "-->\n";
	} else {
		$index = 0;
	}
	
	$link = $xml->channel->item[$index]->link;

	echo "<center><a href=\"" . $link . "\" " .
			outlink($link) . 
	        ">" . $xml->channel->item[$index]->title . "</a></center><br>";
	
	return $link;
}
function print_voting($url) {
	//
	// TODO: Need to update this to Analytics events.
	//
	echo "<center>Rate this recommendation: " .
			"<a href=\"?randomnews=true\" " . vote_good() . ">Good</a>&nbsp;&nbsp;" .
			"<a href=\"?randomnews=true\" " . vote_neutral() . ">Neutral</a>&nbsp;&nbsp;" .
			"<a href=\"?randomnews=true\" " . vote_bad() . ">Bad</a><br>".
			"</center>";
}
//
// Get a typical Url from google news.
//
function get_latest_news() {
	// Call google news Google news rss URL: 
	//$goognewsurl = "http://news.google.com/news?pz=1&cf=all&ned=us&hl=en&topic=h&num=3&output=rss";
	$goognewsurl = "http://news.google.com/news?pz=1&cf=all&ned=us&hl=en&output=rss";
	$nytnewsurl = "http://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml";
	
	$fullurl = get_google_news($goognewsurl);

    // Now get first link from 	
	
	$end = strrpos($fullurl,"&url=");
	$topstoryurl = substr($fullurl,$end+5);
	
	echo "\n<!-- Top Story from google is " . $topstoryurl . "-->\n";
	
	return $topstoryurl;
}
//
// Generate IMage URL and Return string.
//
function print_amazon_book_image($pid,$bookurl) {
	$a = "<center><a href=\"" . $bookurl . "\" title=\"http://images.amazon.com/images/P/" . $pid . "\"" .
		amazon_image_event($bookurl) . ">" .
		"<img src=\"" . "http://images.amazon.com/images/P/" . $pid . "\"></a></center><br>";
	return $a;
	
}
//
// Print out the href for this, the a tag
//
function print_link_to_book($url) {
	return "<center><a href=\"" . $url . "\" " . 
		amazon_event($url) . ">Purchase Book on Amazon.com</a><br></center>";
}
//
// Get a book from sophia classifer
//
function get_book_sync($url) {
	//make a rest call with the url
	//watch the status
	//return final url when done
	$base_url = "http://ccb.cloud.sophiasearch.com/api/AMAZON-BOOKS/metadata/neighbors";
	$resturl = $base_url . "?url=" . $url;
	
	echo "\n<!-- URL is: " . $resturl . "-->\n";

	$str = "";
	$first=true;
	$timeoutcount=2;
	$timeout = 0;
	
	do {
		if($first==true) {
			$first = false;
		} else {
			sleep(10); // wait for pending condition to clear
			$timeoutcount++;
			//echo "waiting 10 seconds<br/>";
			error_log("waited 10 seconds<br/>");
			if($timeoutcount> 2)
				$timeout=1;
		}
		$str = sophia_request_str($resturl);
		
		//echo "strpos pending is " . strpos($str,"code=\"pending\"") .  "<br/>";
		//echo "strpos cached is " . strpos($str,"code=\"cached\"") .  "<br/>";
		$estimate = strpos($str,"estimatedResult=\"true\"");
		//if($estimate != 0)
			//echo "<h4>strpos Estimated is " . $estimate .  "</h4>";
		
		$val = strpos($str,"code=\"pending\"");
	} while(($val + $estimate != 0) || $timeout == 0);
	
//
// Get click through url
//	
	$init_strlen = strlen($str);
    $begin_loc = strpos($str,"srcId");
    $beg_str = substr($str, $begin_loc+7); // god this is ugly.
    $end_pos = strpos($beg_str,"\"");
    $urlstr = substr($beg_str,0,$end_pos); // urlstr is now the correct URL.
    
   echo "\n<!-- Sophia returned this url " . $urlstr . "-->\n";
    
//
// now get the product id
//
    $begin_loc = strpos($str,"srcDocId");
    $beg_str = substr($str,$begin_loc+10); // an abomination
    $end_pos = strpos($beg_str,"\"");
    $pid = substr($beg_str,0,$end_pos);
    
    echo "\n<!-- Sophia returned this pid " . $pid . " -->\n";
    
    //
    // Print voting buttons
    print_voting($urlstr);
    
    // now do the top tag
    echo print_link_to_book($urlstr);
    // Now print the img tag
    echo print_amazon_book_image($pid,$urlstr);
    // now do the a tag
    echo print_link_to_book($urlstr);

    //
    // For the future if async, set up 0 as a return code.
    //
	return 1;
}
//
// format the image, link and url
//
function render_botm_html($dom){
	return "foo";
}
//
function sophia_request_str($url)
{	
	// Initialize the cURL session with the request URL
	$session = curl_init($url); 
	
	// Tell cURL to return the request data
	curl_setopt($session, CURLOPT_RETURNTRANSFER, true); 

	// Execute cURL on the session handle
	$response = curl_exec($session);
	if($response === false) {
		echo "Sophia call results failed<p>";
		return "";
	}
	
	curl_close($session);
	
	return $response;
}

function render_body() {
 
 $nurl = "";
 $nurl = get_latest_news();
 //echo "nurl = " . $nurl . "<br>";
 
 $returl = get_book_sync($nurl);
 //echo "bookurl = " . $returl . "<br>";
 render_botm_html($returl);
 
}
?>